package com.zhiqiang.gameserver.netty;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

/**
 * @author YAO
 */
public class NettyGameServer implements Runnable{
    private static Logger log= LogManager.getLogger(NettyGameServer.class.getName());


    private int port;

    public NettyGameServer(int port) {
        this.port = port;
    }

    @Override
    public void run() {
        try {
            EventLoopGroup bossGroup = new NioEventLoopGroup();
            EventLoopGroup workerGroup = new NioEventLoopGroup();
            try {
                ServerBootstrap sb = new ServerBootstrap();
                sb.group(bossGroup, workerGroup)
                        .channel(NioServerSocketChannel.class)
                        //Runtime.getRuntime().availableProcessors()*2
                        .option(ChannelOption.SO_BACKLOG, 1024)
                        .handler(new LoggingHandler(LogLevel.INFO))
                        .childOption(ChannelOption.SO_KEEPALIVE, true)
                        .childHandler(new NettyGameInitializer());
                // 绑定端口，开始接收进来的连接
                ChannelFuture f = sb.bind(port).sync();
                System.out.println("The game server starts at port " + port + "...");
                f.channel().closeFuture().sync();


            } finally {
                /**
                 * 顾名思义，优雅的关闭
                 */
                workerGroup.shutdownGracefully();
                bossGroup.shutdownGracefully();
            }
        }catch (Exception e){
            e.printStackTrace();
            log.error(e.getMessage());
        }
    }


    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
}
